import SysMenu from "@/api/PMPro/SysMenu";
import Account from "@/api/account/Account";
import SysMenuGrants from "@/api/PMPro/SysMenuGrants";
import utils from "@/utils";
let isFirst = true;
export async function getFormatRoutes(routes, apiName,ProjId) {
  const businessRoutes = routes;
  let pagePermissions = await getPagePermissions(apiName,ProjId);
  utils.transParentId(pagePermissions, pagePermissions);
  formatRoutes(pagePermissions, businessRoutes);
  isFirst = false;
  return [pagePermissions, businessRoutes];
}
export function getButtonPermissions() {
  return new Promise((resolve, reject) => {
    Account.GetMyConfiguration()
      .then(res => {
        const permissions = res.data.permissions
          .filter(item => item.isGranted)
          .map(item => item.name);
        resolve({
          account: res.data.userName,
          name: res.data.name,
          id: res.data.id,
          isAdmin:res.data.isAdmin,
          permissions
        });
      })
      .catch(() => reject());
  });
}
export function getPagePermissions(apiName = "GetMenuTree",ProjId="") {
  return new Promise((resolve, reject) => {
    SysMenuGrants[apiName]({ProjId})
      .then(res => {
        const menus = res.data.items;
        resolve(menus);
      })
      .catch(() => resolve([]));
  });
}
export function getTotalMenus(apiName, page) {
  return new Promise((resolve, reject) => {
    SysMenu[apiName]()
      .then(res => {
        const totalRoutes = createTotalRoutes(res.data.items, page);
        resolve(totalRoutes);
      })
      .catch(() => reject());
  });
}
function formatRoutes(pagePermissions, totalRoutes, currentRoute) {
  if (currentRoute) {
    changeRouteOptions(currentRoute, totalRoutes);
    if (currentRoute.children && currentRoute.children.length) {
      currentRoute.children.forEach(item => {
        formatRoutes(pagePermissions, totalRoutes, item);
      });
    }
  } else {
    pagePermissions.forEach(item => {
      if (item.children && item.children.length) {
        formatRoutes(pagePermissions, totalRoutes, item);
      } else {
        changeRouteOptions(item, totalRoutes);
      }
    });
  }
}
function changeRouteOptions(limitRoute, totalRoutes) {
  // 设置页面权限，显示有权限路由
  const route = utils.getTreeNode({
    tree: totalRoutes,
    key: "path",
    value: limitRoute.component
  });
  if (route) {
    if (route.valid && isFirst) {
      // console.error(
      //   `“菜单名称:${limitRoute.name}”,路由:“${limitRoute.id}”重复定义！`
      // );
      return;
    }
    route.title = limitRoute.name;
    route.icon = limitRoute.ico ? limitRoute.ico : route.icon;
    route.valid = true;
    // 隐藏路由可见
    if (route.children && route.children.length) {
      setSubMenuValid(route);
    }
  }
}
function setSubMenuValid(route) {
  if (route.children && route.children.length) {
    route.children.forEach(item => {
      item.valid = true;
      setSubMenuValid(item);
    });
  }
}

function createTotalRoutes(datas, page) {
  return datas.map(menu => {
    const _component = createComponent(menu, menu.component, page);
    const route = {
      id: menu.id,
      title: menu.name,
      name: menu.component,
      path: menu.component,
      component: _component.component,
      children: createChildren(menu, page)
    };
    if (_component.redirect) {
      route.redirect = _component.redirect;
    }
    return route;
  });
}
function createComponent(menu, path, page) {
  const res = {};
  if (menu.children) {
    res.component = () =>
      Promise.resolve(
        require(`../pages/${page}/views/layout/components/Section.vue`).default
      );
  } else if (menu.submenusComponent && menu.submenusComponent.length) {
    res.component = () =>
      Promise.resolve(
        require(`../pages/${page}/views/layout/components/Section.vue`).default
      );
    res.redirect = `${path}/index`;
  } else {
    res.component = () =>
      Promise.resolve(
        require(`../pages/${page}/views${path}/Index.vue`).default
      );
  }
  return res;
}
function createChildren(menu, page) {
  const routes = [];
  if (menu.children && menu.children.length) {
    menu.children.map(submenu => {
      const _component = createComponent(submenu, submenu.component, page);
      const route = {
        id: submenu.id,
        title: submenu.name,
        name: submenu.component,
        path: submenu.component,
        component: _component.component,
        children: createChildren(submenu, page)
      };
      if (_component.redirect) {
        route.redirect = _component.redirect;
      }
      routes.push(route);
    });
  }
  if (menu.submenusComponent && menu.submenusComponent.length) {
    routes.push(
      ...createSubMenus(
        menu.submenusComponent,
        menu.id,
        menu.component,
        menu.title,
        page
      )
    );
  }
  return routes;
}
function createSubMenus(subMenus, id, path, title, page) {
  return [
    {
      title: title,
      path: `${path}/index`,
      name: `${path}/index`,
      parentId: id,
      component: () =>
        Promise.resolve(
          require(`../pages/${page}/views${path}/Index.vue`).default
        )
    },
    ...createRoutesDeep(subMenus, path, id, page)
  ];
}
function createRoutesDeep(components, path, id, page, routes = []) {
  components.forEach((menu, index) => {
    const curId = id ? id + "-" + index : index;
    routes.push({
      id: curId,
      title: menu.title,
      name: menu.path,
      path: menu.path,
      parentId: id,
      component: () =>
        Promise.resolve(
          require(`../pages/${page}/views${menu.path}/Index.vue`).default
        )
    });
    if (menu.children && menu.children.length) {
      routes.children = createRoutesDeep(
        menu.children,
        menu.path,
        curId,
        page,
        routes
      );
    }
  });
  return routes;
}
